package com.beerq.view_manager;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.alibaba.fastjson.JSONObject;
import com.beerq.R;
import com.beerq.model.UserInfo;
import com.beerq.util.BasicHttp;
import com.beerq.util.BeerQPref;
import com.beerq.util.Constants;
import com.beerq.view.BindPhoneActivity;
import com.beerq.view.MainActivity;
import com.beerq.view.ProductJsManager;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 作者：minj on 2017/9/8 09:36
 * 微信相关的管理类
 */
public class WeChatManager {

    static OkHttpClient mOkHttpClient = new OkHttpClient();

    /***
     * 微信分享
     * @param flag 0分享到到好友 1分享到到朋友圈
     */

    public static void wechatShare(Context context,int flag,String title,String url){
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = url;
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title =title;
        msg.description = "啤气-我们的啤酒世界";
        //这里替换一张自己工程里的图片资源
        Bitmap thumb = BitmapFactory.decodeResource(context.getResources(), R.drawable.logo);
        msg.setThumbImage(thumb);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        req.scene = flag==0?SendMessageToWX.Req.WXSceneSession:SendMessageToWX.Req.WXSceneTimeline;
        Constants.getWXAPI(context).sendReq(req);
    }



    public static void getTokenByCode(final Context context,String code){
        Request request = new Request.Builder().url("https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ Constants.wx_appId+"&secret="+Constants.wx_appSecret+"&code="+code+"&grant_type=authorization_code").build();
        //new call
        Call call = mOkHttpClient.newCall(request);
        //请求加入调度
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                int a=1;
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.message().equals("OK")){
                    JSONObject jsonObject= JSONObject.parseObject(response.body().string());
                    BeerQPref.getInstance(context.getApplicationContext()).setWeChatToken(jsonObject.getString("access_token"));
                    refreshToken(jsonObject.getString("refresh_token"));
                    getUserInfoByToken(context,jsonObject.getString("access_token"),jsonObject.getString("openid"));
                }
            }
        });
    }


    private static void refreshToken(String refresh_token){
        Request request = new Request.Builder().url("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid="+Constants.wx_appId+"&grant_type=refresh_token&refresh_token="+refresh_token).build();
        //new call
        Call call = mOkHttpClient.newCall(request);
        //请求加入调度
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

//                JSONObject jsonObject=JSONObject.parseObject(response.body().string());

            }
        });
    }

    private static void getUserInfoByToken(final Context context,String token,String openId){
        Request request = new Request.Builder().url("https://api.weixin.qq.com/sns/userinfo?access_token="+token+"&openid="+openId).build();
        //new call
        Call call = mOkHttpClient.newCall(request);
        //请求加入调度
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String info=response.body().string();
                final UserInfo userInfo=UserInfo.parseUserinfoFromWeChat(info);



                RegisterAndLoginManager.isAlreadyBindPhone(context, userInfo.getWxNo(), new BasicHttp.IMyCallBack() {
                    @Override
                    public void onResponse(String resonseData) {
                        Intent intent=new Intent(context,MainActivity.class);

                        JSONObject jsonObject= JSONObject.parseObject(resonseData).getJSONObject("Result");

                        UserInfo userInfo1=new UserInfo();

                        userInfo1.setAppUserId(jsonObject.getIntValue("Id"));
                        userInfo1.setPhoneNo(jsonObject.getString("MobileNo"));
                        userInfo1.setUserName(jsonObject.getString("Name"));
                        userInfo1.setHeadPic(jsonObject.getString("HeadPic"));
                        Constants.userInfo=userInfo1;
                        BeerQPref.getInstance(context.getApplicationContext()).setUserInfo(JSONObject.toJSONString(userInfo1));

                        ((Activity)context).runOnUiThread(new Runnable() {
                                                              @Override
                                                              public void run() {
                                                                  ProductJsManager.setUserInfo(Constants.firstWebView, Constants.userInfo.getAppUserId());
                                                              }
                                                          });


                        context.startActivity(intent);
                    }

                    @Override
                    public void onFailure(String resonseData) {
                        Intent intent=new Intent(context,BindPhoneActivity.class);
//                        BeerQPref.getInstance(context.getApplicationContext()).setUserInfo(JSONObject.toJSONString(userInfo));
                        intent.putExtra("USERINFO",JSONObject.toJSONString(userInfo));

                        context.startActivity(intent);
                    }
                });





//                JSONObject jsonObject=JSONObject.parseObject(response.body().string());

            }
        });
    }


}
